import axios from 'axios';

const BASE_URL = process.env.VUE_APP_API_BASE_URL || 'http://localhost:nodejs/api';

const instance = axios.create({
  baseURL: BASE_URL,
  timeout: 30000,
  withCredentials: true, // 允许跨域
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么，例如加入 token
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 404:
          // 处理404
          break;
        default:
          // 处理其他错误
      }
    }
    return Promise.reject(error);
  }
);

// 通用请求方法
const request = async (method, url, data = null, config = {}) => {
  try {
    const response = await instance({
      method,
      url,
      data: method !== 'GET' ? data : null,
      params: method === 'GET' ? data : null,
      ...config,
    });
    return response;
  } catch (error) {
    console.error('Request error:', error);
    throw error;
  }
};

// 流式请求方法
const streamRequest = (method, url, data = null, onChunk, config = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      method,
      url,
      data: method !== 'GET' ? data : null,
      params: method === 'GET' ? data : null,
      responseType: 'stream',
      ...config,
    })
      .then((response) => {
        const reader = response.data.getReader();
        const decoder = new TextDecoder();

        function read() {
          reader.read().then(({ done, value }) => {
            if (done) {
              resolve();
              return;
            }
            const chunk = decoder.decode(value);
            onChunk(chunk);
            read();
          });
        }

        read();
      })
      .catch(reject);
  });
};

// 取消请求
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
const cancelRequest = () => {
  source.cancel('请求被用户取消');
};
export default {
  get: (url, params, config) => request('GET', url, params, config),
  post: (url, data, config) => request('POST', url, data, config),
  stream: (method, url, data, onChunk, config) => streamRequest(method, url, data, onChunk, config),
  cancelRequest,
};